﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using MySql.Data.MySqlClient;
using System.Text.RegularExpressions;
using System.Data.SqlClient;

namespace com.tiyma.components
{
    public class BookJSManager
    {

        #region 数组名字定义
        //热门推荐
        const string m_hot_recommend_arr = "HotRecom";
        /// <summary>
        /// 热门搜索
        /// </summary>
        const string m_hot_search_arr = "HotSearch";
        /// <summary>
        /// 最新更新
        /// </summary>
        const string m_last_update_arr = "LastUpdate";

        /// <summary>
        /// 数组格式
        /// </summary>
        const string m_arr_name_format = "var {0} = new Array({1});";

        /// <summary>
        /// 换行
        /// </summary>
        const string m_new_line = "\r\n";

        /// <summary>
        /// 热门搜索和热门推荐的数量
        /// </summary>
        const int m_top_count = 10;

        /// <summary>
        /// 推荐和搜索模板 bookId,bookName,siteId,siteName,lastUpdateTime
        /// </summary>
        const string m_item_top_template = "{0}[{1}] = new Array('{2}','{3}','{4}','{5}','{6}');";

        /// <summary>
        /// 最新更新模板 categoryName, bookId,bookName,authorName,siteId,siteName,lastUpdateChatperId,lastUpdateChapterName,lastUpdateTime
        /// </summary>
        const string m_item_last_update_template = "{0}[{1}] = new Array('{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}');";

        const string m_file_name = "tiyma.js";

        #endregion

        public void CreateJSByService()
        {
            while (true)
            {
                System.Threading.Thread.Sleep(100);

                CreateJS();

                //5小时一次
                System.Threading.Thread.Sleep(5 * 60 * 60 * 1000);
            }
        }

        public void CreateJS()
        {
            string t_path = AppConfig.BookJSPath;

            string t_file_name = Path.Combine(t_path, m_file_name);

            FileStream t_fs = null;

            string t_top_js = CreateTopBookJS();
            string t_last_js = CreateLastUpdateBookJS();

            if (string.IsNullOrEmpty(t_top_js) || string.IsNullOrEmpty(t_last_js))
                return;

            string t_file_content = t_top_js + t_last_js;

            try
            {
                t_fs = new FileStream(t_file_name, FileMode.Create, FileAccess.Write);
                StreamWriter t_writer = new StreamWriter(t_fs, System.Text.Encoding.UTF8);
                t_writer.WriteLine(t_file_content.Trim());
                t_writer.Flush();
            }
            catch (IOException ex)
            {
                LogHelper.Error("生产Js失败" + ex.Message + ex.Source + ex.GetBaseException().Message);
            }
            catch (Exception e)
            {

            }
            finally
            {
                if (t_fs != null)
                    t_fs.Close();
            }
        }

        /// <summary>
        /// 获取榜单数据
        /// </summary>
        /// <param name="i_type"></param>
        /// <param name="i_count"></param>
        /// <returns></returns>
        public string CreateTopBookJS()
        {
            string t_str_sql = string.Format("select  t.bookid,t.bookname,t.authorname,t.lastupdatetime,t.lastUpdateChapterName,t.ChapterCount, t.siteId,t.siteName from tiyma.tbbook t ,(select bookName from tbHotBook where bookType=0 limit 0,10) tb where t.bookName=tb.bookName and t.lastUpdateChapterName is not null", m_top_count);


            int t_index = 0;
            StringBuilder sb = new StringBuilder();

            List<BookInfo> t_book_list = new List<BookInfo>();

            try
            {
                using (SqlDataReader reader = DataBaseManager.ExecuteReader(t_str_sql))
                {
                   
   
                    while (reader.Read())
                    {
                        BookInfo t_book = new BookInfo();
                        t_book.BookId =reader["bookId"].ToString();
                        t_book.BookName = reader["bookName"].ToString();
                        t_book.SiteId = Convert.ToInt32(reader["SiteId"].ToString());
                        t_book.SiteName = reader["siteName"].ToString();
                        t_book.BookChapterCount = GetChapterCount(Convert.ToInt32(reader["ChapterCount"].ToString()), reader["lastUpdateChapterName"].ToString());
                        t_book_list.Add(t_book);

                    }
                }

                if (t_book_list != null && t_book_list.Count > 0)
                {
                    t_book_list.Sort(delegate(BookInfo t_a, BookInfo t_b)
                    {
                        if (t_b.BookChapterCount > t_a.BookChapterCount)
                            return 1;
                        else if (t_a.BookChapterCount == t_b.BookChapterCount)
                            return 0;
                        return -1;
                    });
                }
                else
                {
                    return string.Empty;
                }

                sb.AppendLine("\r\n //热门搜索列表");
                sb.AppendFormat(m_arr_name_format, m_hot_search_arr, m_top_count).Append(m_new_line);

                Dictionary<string, string> t_dic_book = new Dictionary<string, string>();
                foreach (BookInfo t_book in t_book_list)
                {
                    if (!t_dic_book.ContainsKey(t_book.BookName))
                    {
                        sb.AppendFormat(m_item_top_template,
                              m_hot_search_arr, t_index
                              , t_book.BookId
                              , t_book.BookName.ToString().Replace("'", "")
                              , t_book.SiteId
                              , t_book.SiteName
                              , "").Append(m_new_line);
                        t_index++;
                        t_dic_book.Add(t_book.BookName, t_book.BookName);
                        if (t_index >= m_top_count)
                            break;
                    }
                }

               
                t_index = 0;
                t_book_list = new List<BookInfo>();

                t_str_sql = string.Format("select  t.bookid,t.bookname,t.authorname,t.lastupdatetime,t.lastUpdateChapterName,t.ChapterCount, t.siteId,t.siteName from tiyma.tbbook t ,(select bookName from tbHotBook where bookType=1 limit 0,10) tb where t.bookName=tb.bookName and t.lastUpdateChapterName is not null", m_top_count);

                using (SqlDataReader reader = DataBaseManager.ExecuteReader(t_str_sql))
                {


                    while (reader.Read())
                    {
                        BookInfo t_book = new BookInfo();
                        t_book.BookId = reader["bookId"].ToString();
                        t_book.BookName = reader["bookName"].ToString();
                        t_book.SiteId = Convert.ToInt32(reader["SiteId"].ToString());
                        t_book.SiteName = reader["siteName"].ToString();
                        t_book.BookChapterCount = GetChapterCount(Convert.ToInt32(reader["ChapterCount"].ToString()), reader["lastUpdateChapterName"].ToString());
                        t_book_list.Add(t_book);

                    }
                }

                if (t_book_list != null && t_book_list.Count > 0)
                {
                    t_book_list.Sort(delegate(BookInfo t_a, BookInfo t_b)
                    {
                        if (t_b.BookChapterCount > t_a.BookChapterCount)
                            return 1;
                        else if (t_a.BookChapterCount == t_b.BookChapterCount)
                            return 0;
                        return -1;
                    });
                }
                else
                {
                    return string.Empty;
                }

                t_dic_book = new Dictionary<string, string>();
            
                sb.AppendLine("\r\n//热门推荐列表");
                sb.AppendFormat(m_arr_name_format, m_hot_recommend_arr, m_top_count).Append(m_new_line);
                foreach(BookInfo t_book in t_book_list)
                {
                    if (!t_dic_book.ContainsKey(t_book.BookName))
                    {
                        sb.AppendFormat(m_item_top_template,
                            m_hot_recommend_arr, t_index
                            , t_book.BookId
                            , t_book.BookName.Replace("'", "")
                            , t_book.SiteId
                            , t_book.SiteName
                            , "").Append(m_new_line);
                        t_index++;
                        t_dic_book.Add(t_book.BookName, t_book.BookName);
                        if (t_index >= m_top_count)
                            break;
                    }

                }
                
                return sb.ToString();
            }
            catch (Exception ex)
            {
                LogHelper.Error("生产榜单数据失败" + ex.ToString());

                return string.Empty;
            }
        }

        /// <summary>
        /// 获取最新更新小说
        /// </summary>
        /// <param name="i_count"></param>
        /// <returns></returns>
        public string CreateLastUpdateBookJS()
        {
            string t_str_sql = "select  t.bookid,t.bookname,t.authorname,t.lastupdatechapterid,t.lastupdatechaptername,t.lastupdatetime,t.siteId,t.siteName,t.CategoryName from tiyma.tbbook t,";
            t_str_sql += string.Format("(select bookName, max(chaptercount) chaptercount from tbbook where lastupdatetime>DATE_FORMAT(NOW(), '%Y-%m-%d' ) group by bookName order by lastUpdateTime desc limit 0,{0}) tb  where t.bookname=tb.bookname and t.chaptercount=tb.chaptercount order by t.lastupdatetime desc", AppConfig.UpdateBookCount);
           
            StringBuilder sb = new StringBuilder();
            int t_index = 0;
            try
            {
                using (SqlDataReader reader = DataBaseManager.ExecuteReader(t_str_sql))
                {
                    sb.AppendLine("\r\n//最新更新列表");
                    sb.AppendFormat(m_arr_name_format, m_last_update_arr, AppConfig.UpdateBookCount).Append(m_new_line);
                    while (reader.Read())
                    {
                        sb.AppendFormat(m_item_last_update_template,
                           m_last_update_arr, t_index
                           , reader["CategoryName"].ToString().Trim().Length == 2 ? reader["CategoryName"].ToString().Trim() + "小说" : reader["CategoryName"].ToString().Trim()
                           , reader["bookid"].ToString()
                           , reader["bookName"].ToString().Replace("'","")
                           , reader["authorname"].ToString().Replace("'", "")
                           , reader["siteId"].ToString()
                           , reader["siteName"].ToString()
                           , reader["lastupdatechapterid"].ToString()
                           , reader["lastupdatechaptername"].ToString().Replace("'", "")
                           , Convert.ToDateTime(reader["lastupdatetime"].ToString()).Day == DateTime.Now.Day ? "今天" : "一天之前").Append(m_new_line);
                        t_index++;

                        if (t_index >= AppConfig.UpdateBookCount)
                            break;
                    }
                }

                return sb.ToString();
            }
            catch (Exception ex)
            {
                LogHelper.Error("生产最新更新列表失败" + ex.ToString());
                return string.Empty;
                
            }

        }

        /// <summary>
        /// 根据最后章节名称获取章节总数
        /// </summary>
        /// <param name="i_chapter_count"></param>
        /// <param name="i_last_update_chapter_name"></param>
        /// <returns></returns>
        public int GetChapterCount(int i_chapter_count, string i_last_update_chapter_name)
        {

            if (string.IsNullOrEmpty(i_last_update_chapter_name))
                return i_chapter_count;


            string[] t_big_chinese = new string[] { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖", "拾", "佰", "仟", "〇" };
            string[] t_small_chinese = new string[] { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "百", "千", "〇" };
            string[] t_number = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "十", "百", "千", "0" };

            for (int index = 0; index < t_big_chinese.Length; index++)
            {

                i_last_update_chapter_name = i_last_update_chapter_name.Replace(t_big_chinese[index], t_number[index]);
                i_last_update_chapter_name = i_last_update_chapter_name.Replace(t_small_chinese[index], t_number[index]);
            }

            i_last_update_chapter_name = Regex.Replace(i_last_update_chapter_name, "(\\d+)千(\\d+)百(\\d+)十(\\d+)", "$1$2$3$4", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_last_update_chapter_name = Regex.Replace(i_last_update_chapter_name, "(\\d+)千(\\d+)百(\\d+)", "$1$2$3", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_last_update_chapter_name = Regex.Replace(i_last_update_chapter_name, "(\\d+)千(\\d+)", "$1$2", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_last_update_chapter_name = Regex.Replace(i_last_update_chapter_name, "(\\d+)千", "$1^000", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_last_update_chapter_name = Regex.Replace(i_last_update_chapter_name, "(\\d+)百(\\d+)十(\\d+)", "$1$2$3", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_last_update_chapter_name = Regex.Replace(i_last_update_chapter_name, "(\\d+)百(\\d+)", "$1$2", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_last_update_chapter_name = Regex.Replace(i_last_update_chapter_name, "(\\d+)百", "$1^00", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_last_update_chapter_name = Regex.Replace(i_last_update_chapter_name, "(\\d+)十(\\d+)", "$1$2", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_last_update_chapter_name = Regex.Replace(i_last_update_chapter_name, "(\\d+)十", "$1^0", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_last_update_chapter_name = Regex.Replace(i_last_update_chapter_name, "十(\\d+)", "1$1", RegexOptions.IgnoreCase | RegexOptions.Compiled);

            i_last_update_chapter_name = i_last_update_chapter_name.Replace("^", "").Replace("十", "10");

            Match t_mc = Regex.Match(i_last_update_chapter_name, "(\\d+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            if (t_mc != null && t_mc.Groups.Count > 1)
            {
                int t_chapter_count = 0;
                if (!int.TryParse(t_mc.Groups[1].Value.ToString(), out t_chapter_count))
                    t_chapter_count = 0;

                if (t_chapter_count != 0)
                    return t_chapter_count;
            }

            return i_chapter_count;

        }

    }
}
